package com.vf.admin.fiwork.util;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.vf.admin.common.Constants;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;

public class SampleUtil {

    // 设置APPID/AK/SK
    // 初始化一个AipFace
    public static final AipFace client = new AipFace(Constants.BD_APP_ID, Constants.BD_API_KEY, Constants.BD_SECRET_KEY);

    //人脸比对符合条件分数
    public static final BigDecimal Fraction = new BigDecimal("80");

    /**
     * 检测用户上传的图片
     * @param image
     * @return
     */
    public static String detect(String image) {

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
        // client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
        // client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 调用接口
        String imageType = "URL";
        //检测参数配置
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("face_field", "age");
        options.put("max_face_num", "2");
        options.put("face_type", "LIVE");
        options.put("liveness_control", "LOW");
        // 人脸检测
        JSONObject res = client.detect(image, imageType, options);
        return  res.toString(2);
    }

    /**
     * 人相1对1比对
     * @param image1
     * @param image2
     * @return
     */
    public static boolean pk(String image1,String image2){
        // image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
        MatchRequest req1 = new MatchRequest(image1, "URL");
        MatchRequest req2 = new MatchRequest(image2, "BASE64");
//        MatchRequest req1 = new MatchRequest(image1, "BASE64");
//        MatchRequest req2 = new MatchRequest(image2, "BASE64");
        ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
        requests.add(req1);
        requests.add(req2);
        JSONObject res = client.match(requests);
        String result = res.toString(2);
        com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(result);
        if(json.getString("error_msg").equals("SUCCESS") && json.getInteger("error_code").equals(0)){
            //获取比对评分
            com.alibaba.fastjson.JSONObject people = json.getJSONObject("result");
            if(new BigDecimal(people.getString("score")).compareTo(Fraction) >= 0) return true;
            return false;
        }else{
            return false;
        }
    }
}
